package com.demo.controller;

import com.demo.task.TestTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ScheduledFuture;

/**
 * @author Chen Wei
 * @date 2021-01-27 09:04
 */
@RestController
@RequestMapping("/cron")
@Component
public class TaskController {

    /**
     * 定时任务名称
     */
    private String taskName = "【定时任务：测试】";

    /**
     * 每隔3秒
     */
    private String cron = "0/3 * * * * *";

    /**
     * ThreadPoolTaskScheduler：线程池任务调度类，能够开启线程池进行任务调度。
     * ThreadPoolTaskScheduler.schedule()方法会创建一个定时计划ScheduledFuture，在这个方法需要添加两个参数，
     * Runnable（线程接口类） 和CronTrigger（定时任务触发器）
     */
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private ScheduledFuture<?> future;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    /**
     * 启动定时任务
     * @return
     */
    @GetMapping("/start")
    public String startCron() {
        future = threadPoolTaskScheduler.schedule(new TestTask(), new CronTrigger(cron));
        System.out.println("启动" + taskName + "cron为：" + cron);
        return "启动" + taskName;
    }

    @GetMapping("/stop")
    public String stopCron() {
        if (future != null) {
            System.out.println("关闭" + taskName);
            future.cancel(true);
            return taskName + "已关闭";
        }
        return taskName + "未开启";
    }

    @GetMapping("/restart")
    public String restart(@RequestParam("cron") String cron) {
        this.stopCron();
        future = threadPoolTaskScheduler.schedule(new TestTask(), new CronTrigger(cron));
        System.out.println("重启" + taskName + "cron: " + cron);
        return "重启" + taskName;
    }

    @GetMapping("/isCancelled")
    public String isCancelled() {
        if (future != null) {
            boolean cancelled = future.isCancelled();
            return taskName + "是否取消：" + cancelled;
        }
        return taskName + "未开启";
    }

}
